package cc.cix.hq.file.service.impl;

import cc.cix.hq.common.core.client.IFileClient;
import cc.cix.hq.common.core.entity.org.File;
import cc.cix.hq.common.core.entity.org.User;
import cc.cix.hq.common.core.exception.HqException;
import cc.cix.hq.common.core.utils.HqUtil;
import cc.cix.hq.file.mapper.FileMapper;
import cc.cix.hq.file.properties.MinIoProperties;
import cc.cix.hq.file.service.IFileService;
import cc.cix.hq.file.util.MinioUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cix
 * @since 2022-06-04
 */
@Service
@org.apache.dubbo.config.annotation.Service(interfaceClass = IFileClient.class)
@Slf4j
@RequiredArgsConstructor
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService, IFileClient {

    private final MinIoProperties minIoProperties;

    @Override
    public List<File> upload(List<MultipartFile> files) {
        if (CollectionUtil.isEmpty(files)) {
            throw new HqException("上传文件不能为空");
        }

        // 上传文件到 Minio
        MinioUtil.putObject(files, minIoProperties.getBucketName());

        // 将文件信息保存到数据库
        User user = HqUtil.getCurrentUser();
        List<File> newFiles = new ArrayList<>();
        files.forEach(file -> {
            try {
                String url = MinioUtil.getPresignedObjectUrl(minIoProperties.getBucketName(), file.getOriginalFilename(), 9999);
                File newFile = new File();
                newFile.setUserId(user.getId());
                newFile.setUrl(url);
                newFile.setFileName(file.getOriginalFilename());
                newFile.setFileSize(file.getSize());
                newFile.setBucketName(minIoProperties.getBucketName());
                newFiles.add(newFile);
            } catch (Exception e) {
                throw new HqException("生成访问链接失败");
            }
        });
        saveBatch(newFiles);

        return newFiles;
    }

    @Override
    public void delete(String id) {
        try {
            File file = getById(id);
            MinioUtil.removeObject(file.getBucketName(), file.getFileName());
        } catch (Exception e) {
            log.error("文件删除失败：e={}", e.getMessage());
            throw new HqException("删除失败");
        }
    }
}
